/**
 * @file 学部看板报表
 * @author ruanairuo(ruanairuo@baijia.com)
 * @date 2020-03-18
 */
import React, {useEffect, useState, useRef} from 'react';
import {Card, Row, Col} from 'antd';
import CommonSearchBar from '~/page/FineBi/common/CommonSearchBar';
import {querySelectOptions} from '~/service/refundReport';
import {convertSearcherParams} from '~/page/FineBi/utils/convert';
import {userRoundIdx, initUserRoundIdx} from '~/utils/const';
import BarAndLineChart from '../BarAndLine';

const SELECT_UNIT_ID = 'DepartmentDimensionReport_PartOne_select';
const dIdPre = 'DepartmentDimensionReport_PartOne_select';

const searchConfig = [
    {
        type: 'select',
        key: 'department',
        label: '学部',
        optionsConfig: {
            options: [],
            pager: {}
        },
        props: {}
    }
];

export default function CompositeYieldRate(props) {
    const initDemenstion = props.initPropDimensionAndValues;
    const [selectOptions, setSelectOptions] = useState({});
    // 共同查询条件
    const [dimensionAndValues, setDimensionAndValues] = useState(initDemenstion);
    const [isSearch, setIsSearch] = useState(false);
    const [defaultDepartment, setDefaultDepartment] = useState([]);
    const formRef = useRef();

    useEffect(() => {
        const findItem = initDemenstion.find(item => item.dimensionName === userRoundIdx);
        findItem.value = [props.userRoundValue];

        setDimensionAndValues([
            ...initDemenstion,
            {
                dimensionId: 'department',
                dimensionName: 'department',
                value: [defaultDepartment]
            }
        ]);
        formRef.current.formFields.resetFields();
        formRef.current.formFields.setFieldsValue({
            department: [defaultDepartment]
        });
    }, [props.userRoundValue]);

    const handleOk = fieldsValue => {
        const params = convertSearcherParams(fieldsValue);
        setDimensionAndValues([...params, {...props.initPropDimensionAndValues[0], value: [props.userRoundValue]}]);
    };

    const handleReset = e => {
        setDimensionAndValues([
            {
                dimensionId: 'department',
                dimensionName: 'department',
                value: [defaultDepartment]
            },
            {...props.initPropDimensionAndValues[0], value: [props.userRoundValue]}
        ]);
        formRef.current.formFields.setFieldsValue({
            department: [defaultDepartment]
        });
    };

    // 选项查询
    const handleFetchOptions = (options, defaultKey) => {
        const {key, searchKey, pager, isGetingMore, options: curOptions, fieldsValue = []} = options;
        let permissions = searchConfig.map(item => ({
            dimensionId: `${dIdPre}_${item.key}`,
            dimensionName: item.key,
            filterItems: Array.isArray(fieldsValue[item.key])
                ? fieldsValue[item.key]
                : fieldsValue[item.key] == null
                    ? []
                    : [fieldsValue[item.key]]
        }));

        permissions = permissions.filter(item => (item.filterItems?.length && item.dimensionName !== userRoundIdx));
        permissions.push({...props.initPropDimensionAndValues[0], value: [props.userRoundValue]});

        const params = {
            pager,
            dimensionId: `${dIdPre}_${key}`,
            dimensionName: key,
            searchKey,
            permissions,
            unitId: SELECT_UNIT_ID
        };

        querySelectOptions(params).then(res => {
            const {data = [], pager} = res;
            if (defaultKey) {
                if (data?.length > 0) {
                    setDefaultDepartment(data[0]);
                }
                formRef.current.formFields.setFieldsValue({
                    [defaultKey]: data?.length > 0 ? [data[0]] : []
                });
                const dimension = [...dimensionAndValues];
                const defaultKeyIndex = dimension.findIndex(ele => ele.key === defaultKey);
                if (defaultKeyIndex > -1) {
                    dimension[defaultKeyIndex] = data?.length > 0 ? [data[0]] : [];
                }
                else {
                    dimension.push({
                        dimensionId: defaultKey,
                        dimensionName: defaultKey,
                        value: data?.length > 0 ? [data[0]] : []
                    });
                }
                setDimensionAndValues(dimension);
                setIsSearch(true);
            }
            let options =
                data.map(item => ({
                    key: item,
                    value: item,
                    label: item
                })) || [];
            // 分页时，累加展示
            if (isGetingMore) {
                options = curOptions.concat(options);
            }
            setSelectOptions({key, options, pager});
        });
    };
    useEffect(() => {
        handleFetchOptions({key: searchConfig[0].key}, searchConfig[0].key);
    }, []);
    return (
        <div>
            <Card style={{marginBottom: 8}}>
                <CommonSearchBar
                    noCache
                    config={searchConfig}
                    initialValues={{}}
                    onOk={handleOk}
                    onReset={handleReset}
                    onfetchOptions={handleFetchOptions}
                    selectOptions={selectOptions}
                    ref={formRef}
                />
            </Card>
            <Card>
                <Row>
                    <Col span={12}>
                        <BarAndLineChart
                            dId="DepartmentDimensionReport_PartOne"
                            unitId="DepartmentDimensionReport_PartOne_composite"
                            dimensionAndValues={dimensionAndValues}
                            isSearch={isSearch}
                            selectId={SELECT_UNIT_ID}
                        />
                    </Col>
                    <Col span={12}>
                        <BarAndLineChart
                            dId="DepartmentDimensionReport_PartTwo"
                            unitId="DepartmentDimensionReport_PartTwo_composite"
                            dimensionAndValues={dimensionAndValues}
                            isSearch={isSearch}
                            selectId={SELECT_UNIT_ID}
                        />
                    </Col>
                </Row>
            </Card>
        </div>
    );
}
